package cdu.javaendwork.Controller.AdoptionMore;

import cdu.javaendwork.model.sqlModel.Post;
import cdu.javaendwork.model.sqlModel.User;
import cdu.javaendwork.service.Impl.AdoptionMore.PostServiceImpl;
import cdu.javaendwork.service.Impl.User.UserServiceImpl;
import cdu.javaendwork.service.Interface.AdoptionMore.PostService;
import cdu.javaendwork.service.Interface.User.UserService;
import cdu.javaendwork.util.pageHelp.PageHelper;
import cdu.javaendwork.util.pageHelp.PageInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/ones_post_list")
public class OnesPostListController extends HttpServlet {
    PageHelper pageHelper = new PageHelper();
    UserService userService=new UserServiceImpl();
    PostService postService=new PostServiceImpl();
    @Override
    public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sPage = req.getParameter("page");
        String postKeys=req.getParameter("postKeys");
        String uid = req.getParameter("userid");
        int userid=(uid == null || uid.equals("")) ? 0 : Integer.parseInt(uid);
        //如果没有传入id 则说明是要修改自己的个人资料 将id改成自己
        if(userid == 0)
        {
            HttpSession session = req.getSession();
            User me= (User)session.getAttribute("user");
            userid = me.getId();
        }
        req.setAttribute("postKey",postKeys);
        int pageSize=3;
        int pageIndex = (sPage == null || sPage.equals("")) ? 1 : Integer.parseInt(sPage);

        User user = userService.findById(userid);


        PageInfo pageInfo = pageHelper.filter("Post","status=1 and userid="+userid,pageIndex,pageSize);


        List<Post> postList=new ArrayList<>();
        if(postKeys==null||postKeys.equals("")) {
            postList = postService.filterByUserIdLimit(userid,pageIndex, pageSize);
        }else {
            String sql="status=1 and (title like '%" + postKeys + "%' or content like '%"+postKeys+"%' ) and (userid="+userid+")";
            pageInfo=pageHelper.filter("Post",sql,pageIndex,pageSize);
            postList=postService.filterByTitleAndContentAndUserIdLimit(postKeys,userid,pageIndex,pageSize);
        }
        req.setAttribute("user",user);
        req.setAttribute("posts",postList);
        req.setAttribute("pageInfo",pageInfo);

        req.getRequestDispatcher("postsOfSomeOne.jsp").forward(req,resp);
    }
}
